import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/api/mohu.dart';
import 'package:wallpaper/components/input/my_search_input.dart';
import 'package:wallpaper/components/video/video_list.dart';
import 'package:wallpaper/generated/l10n.dart';
import 'package:wallpaper/model/options_base.dart';
import 'package:wallpaper/model/random_video_base.dart';
import 'dart:async';

class VideoSearch extends StatefulWidget {
  final String type;
  const VideoSearch({super.key, required this.type});

  @override
  State<VideoSearch> createState() => _VideoSearchState();
}

class _VideoSearchState extends State<VideoSearch> {
  final TextEditingController controller = TextEditingController();
  final int limit = 30; // 常量使用final
  int page = 1;
  final List<VideoBaseInfo> videos = []; // 使用final列表
  bool isLoading = false;

  // 用于取消延时器
  Timer? _refreshTimer;
  // 用于跟踪刷新操作
  Completer<void>? _refreshCompleter;

  Future<void> getVideoWallpaper() async {
    if (isLoading) return; // 防止重复加载
    setState(() {
      isLoading = true;
    });

    if (!mounted) return;

    try {
      Response res;
      if (widget.type == 'pc') {
        res = await getDuBaVideoWallpaperPC(
            limit: limit, page: page, msg: controller.text);
      } else {
        res = await getDuBaVideoWallpaper(
            limit: limit, page: page, msg: controller.text);
      }

      if (res.data['code'] == 200) {
        List datas = res.data['data'];
        if (datas.isEmpty) {
          BotToast.showText(text: S.of(context).s25);
        }

        // 临时列表存储新数据，减少setState调用次数
        final newVideos = <VideoBaseInfo>[];
        for (var i = 0; i < datas.length; i++) {
          newVideos.add(VideoBaseInfo(
            cover: datas[i]['phone_img_url'],
            height: 1920,
            width: 1080,
            url: datas[i]['video_url'],
            tag: datas[i]['decs'].replaceAll(',', ' '),
          ));
        }

        // 批量添加，减少重建
        setState(() {
          videos.addAll(newVideos);
        });
      }
    } catch (e) {
      print('视频加载错误: $e');
    } finally {
      if (mounted) {
        setState(() {
          isLoading = false;
        });
      }
    }
  }

  // 提取搜索提交处理方法
  void _handleSearchSubmitted(String value) {
    FocusScope.of(context).unfocus(); // 更简洁的失焦方式
    videos.clear();
    page = 1;
    getVideoWallpaper();
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    // 取消定时器
    _refreshTimer?.cancel();

    // 确保在组件销毁时完成任何未完成的刷新操作
    if (_refreshCompleter != null && !_refreshCompleter!.isCompleted) {
      _refreshCompleter!.complete();
    }

    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;

    // 使用RepaintBoundary隔离重绘区域
    return RepaintBoundary(
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          toolbarHeight: 0,
          elevation: 0,
          backgroundColor: theme.primaryContainer,
          surfaceTintColor: theme.primaryContainer,
          leading: null,
        ),
        body: Column(
          children: [
            // 搜索框独立封装
            const RepaintBoundary(
              child: _SearchInputWidget(),
            ),
            Expanded(
              child: VideoList(
                  videoList: videos,
                  isLoading: isLoading,
                  isPC: widget.type == 'pc',
                  onImageBottomLoading: () {
                    if (!isLoading) {
                      page++;
                      getVideoWallpaper();
                    }
                  },
                  onImageListRefresh: () {
                    // 取消现有的定时器（如果有）
                    _refreshTimer?.cancel();

                    // 创建新的 Completer 来处理刷新操作
                    _refreshCompleter = Completer<void>();

                    videos.clear();
                    page = 1;
                    getVideoWallpaper();

                    // 设置延时自动完成刷新
                    _refreshTimer = Timer(
                        Duration(milliseconds: OptionsBase().refreshTime), () {
                      if (_refreshCompleter != null &&
                          !_refreshCompleter!.isCompleted) {
                        _refreshCompleter!.complete();
                      }
                    });

                    return _refreshCompleter!.future;
                  }),
            ),
          ],
        ),
      ),
    );
  }
}

// 搜索框独立组件，减少重建范围
class _SearchInputWidget extends StatelessWidget {
  const _SearchInputWidget();

  @override
  Widget build(BuildContext context) {
    // 获取父组件状态
    final parentState = context.findAncestorStateOfType<_VideoSearchState>()!;

    return MySearchInput(
      controller: parentState.controller,
      onSubmitted: (v) => parentState._handleSearchSubmitted(v),
    );
  }
}
